#pragma once
#include <iostream>
#include <string>
#include <functional>
#include <pthread.h>

namespace ThreadMoudle
{
    // template <class K, class T>
    // class ThreadData
    // {
    // public:
    //     ThreadData(const std::string &name, pthread_mutex_t* mutex)
    //         : _name(name), _mutex(mutex)
    //     {
    //     }

    // public:
    //     std::string _name;
    //     pthread_mutex_t* _mutex;
    // };
    // template<class T>
    using func_t = std::function<void(std::string)>;
    class Thread
    {
    public:
        // typedef void (*func_t)(ThreadData *mutex);
        Thread(const std::string &name, const func_t &func)
            : _name(name), _func(func)
        {
        }
        void Excute()
        {
            _isrunning = true;
            _func(_name);
            _isrunning = false;
        }
        static void *ThreadRoutine(void *args)
        {
            Thread *self = static_cast<Thread *>(args);
            self->Excute();
            return nullptr;
        }
        bool start()
        {
            int n = pthread_create(&_tid, nullptr, ThreadRoutine, this);
            if (n != 0)
                return false;
            return true;
        }
        void stop()
        {
            if (_isrunning)
            {
                pthread_cancel(_tid);
                _isrunning = false;
            }
        }
        void join()
        {
            pthread_join(_tid, nullptr);
        }
        ~Thread()
        {
        }

    private:
        pthread_t _tid;
        std::string _name;
        bool _isrunning;
        func_t _func; // 回调方法，要以_func()运行。
    };
};